<?php
// +----------------------------------------------------------------------
// | Created by PHPstorm: [ JRK丶Admin ]
// +----------------------------------------------------------------------
// | Copyright (c) 2019~2022 [LuckyHHY] All rights reserved.
// +----------------------------------------------------------------------
// | SiteUrl: http://www.luckyhhy.cn
// +----------------------------------------------------------------------
// | Author: LuckyHhy <jackhhy520@qq.com>
// +----------------------------------------------------------------------
// | Date: 2020/6/26 0026
// +----------------------------------------------------------------------
// | Description:
// +----------------------------------------------------------------------

namespace app\admin\controller;


use app\api\service\HaiDing;
use app\common\controller\AdminBaseController;
use app\common\model\tang\BalanceLog;
use app\common\model\tang\Cost;
use app\common\model\tang\CostLog;
use app\common\model\tang\CostRule;
use app\common\model\tang\CostSectionPay;
use app\common\model\tang\Merchant as MerchantModel;
use app\common\model\tang\CostAudit as CostAuditModel;
use app\common\model\tang\CostType;
use app\common\model\tang\StaffRule;
use app\common\model\tang\SubjectList;
use think\facade\Db;

class CostAuditCost extends AdminBaseController
{
    protected function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        $this->model = new CostAuditModel();
    }

    public function index()
    {
        if (IS_AJAX) {
            return $this->model->getAdminPageData($this->param, 'id desc');
        }
        $merchant_list = getMerchant();
        $this->assign(compact("merchant_list"));
        return $this->fetch();
    }

    public function costEdit()
    {
        $id = $this->request->param("id/d");//父id
        $info = $this->model->find($id)->toArray();
        $idArr = explode(',', $info['cost_id']);
        $list = [];
        foreach ($idArr as $k => $v) {
            $result = \app\common\model\tang\Cost::with(['merchants', 'costType'])->find($v)->toArray();
            if($result){
                $result['start_time'] = date('Y-m-d',$result['start_time']);
                $result['end_time'] = date('Y-m-d',$result['end_time']);
            }
            $list[] = $result;
        }
        $this->assign(compact("info", 'list'));

        return $this->fetch();
    }

    /**
     *审核通过
     */
    public function UpdateCost()
    {
        $HDService = new HaiDing();
        $id = $this->request->param("id/d");//父id
        $remark = $this->request->param('remark');//父id
        $pay_status = $this->request->param('pay_status');//父id
        $info = $this->model->find($id);
        $idArr = explode(',', $info['cost_id']);
        $merchantInfo = (new MerchantModel())->find($info['merchant_id']);
        if (empty($merchantInfo)) {
            return self::JsonReturn('商户信息不存在', 0);
        }
        Db::startTrans();
        try {
            if (count($idArr) > 1) {
                $all_amount = Cost::whereIn('id', $idArr)->sum('amount');
                if ($pay_status == 1) {
                    if ($all_amount > $info['in_amount']) {
                        return self::JsonReturn('批量转账不支持部分缴费', 0);
                    }
                    if ($all_amount < $info['in_amount']) {//如果转账金额高于账单应付金额
                        $duo = bcsub($info['in_amount'], $all_amount);

                        $balanceModel = new BalanceLog();
                        $bool = BalanceLog::create([
                            'order_sn' => OrderSn(),
                            'mobile' => $merchantInfo['mobile'],
                            'amount' => $duo,
                            'service_charge' => 0,
                            'merchant_id' => $info['merchant_id'],
                            'is_top_up' => 1,
                            'edit' => 1,
                            'type' => 2,
                            'status' => 1,
                            'remark' => '支付订单多出的转账自动冲入余额',
                            'charge_time' => time(),
                            'create_time' => time(),
                        ]);
                        //商户余额自动增加
                        (new MerchantModel())->update(['balance' => bcadd($merchantInfo['balance'], $duo)], ['id' => $merchantInfo['id']]);
                        //多的转移到商户余额中去
                    }
                }
                foreach ($idArr as $k => $v) {
                    $costInfo=[];
                    $payInfo = [];
                    if ($pay_status == 1) {
                        $costInfo = Cost::find($v);

                        $section = new CostSectionPay(); //部分缴费
                        $section->merchant_id = $costInfo['merchant_id'];
                        $section->transaction_id = '';
                        $section->all_amount = $costInfo['all_amount'];
                        $section->cost_id = $v;
                        $section->amount = $costInfo['amount'];
                        $section->balance_amount = 0;
                        $section->create_time = time();
                        $section->update_time = time();
                        $section->type = 3;
                        $section->save();

                        if (!empty($costInfo['billid'])) {
                            $payInfo['direction'] = 1;
                            $payInfo['paymentMethod'] = 'APP';
                            $payInfo['paymentOrderId'] = $costInfo['order_sn'];
                            $payInfo['dealer'] = [
                                'uuid' => '8a0293a988c2d2120188c32b25870098',
                                'code' => 'mianbei',
                                'name' => '米安贝',
                            ];
//                            $payInfo['paymentDate'] = date('Y-m-d H:i:s', time());
                            $payInfo['paymentDate'] = $info['up_time'].' 13:13:13';
//                            $payInfo['incomeDate'] = date('Y-m-d H:i:s', time());
                            $payInfo['incomeDate'] = $info['up_time'].' 13:13:13';
                            $payInfo['remark'] = '微信小程序收款';
                            $payInfo['sourceType'] = 'cre_other';
                            $payInfo['lines'] = [
                                [
                                    'accId' => $costInfo['billid'],
                                    'total' => $costInfo['amount'] / 100,
                                    'paymentType' => [
                                        'uuid' => '8a0289aa736f21880173bc84e7a36fa5',
                                        'code' => '002',
                                        'name' => '转账',
                                    ],
                                    'bankCode' => '',
                                    'poundage' => ''
                                ]
                            ];
                            $result = $HDService->payInfo($payInfo);
                            $costLogInfo = new CostLog();
                            $costLog['cost_id'] = $costInfo['id'];
                            $costLog['request_info'] = json_encode($payInfo);
                            $costLog['responce_info'] = json_encode($result);
                            $costLog['happen_time'] = date('Y-m-d H:i:s', time());
                            $costLog['create_time'] = time();
                            $costLog['update_time'] = time();
                            $costLogInfo->save($costLog);
                            \app\common\model\tang\Cost::update([
                                'subject_id' => 3,
                                'pay_status' => $pay_status,
                                'return_billid' => $result['billNumber'],
                                'pay_time' => date('Y-m-d H:i:s', time()),
                                'bill_no' => getBill(),
                                'amount' => 0,
                                'pay_amount' => $costInfo['amount'],
                            ], ['id' => $costInfo['id']]);
                        } else {
                            if(in_array($costInfo['cost_type_id'],[51,52,53,54,55,56,57])){
                                $costTypeInfo=[];
                                $receipt = [];
                                $costTypeInfo = (new CostType())->where('id',$costInfo['cost_type_id'])->find();
                                $receipt['unitCode'] = $merchantInfo['store_code'];
                                $receipt['counterpartCode'] = $merchantInfo['tenant_code'];
                                $receipt['dealer'] = [
                                    'uuid' => '8a0293a988c2d2120188c32b25870098',
                                    'code' => 'mianbei',
                                    'name' => '米安贝',
                                ];
                                $receipt['paymentOrderId'] = $costInfo['order_sn']; //订单编号
                                $receipt['contractCode'] = $merchantInfo['code'];//合同号
                                $receipt['paymentTypeCode'] = '002'; //付款方式代码
//                                $receipt['depositDate'] =date( 'Y-m-d H:i:s',strtotime($info['up_time'])); //预存日期（收款日期）
                                $receipt['depositDate'] =$info['up_time'].' 13:13:13';; //预存日期（收款日期）
//                                $receipt['accountDate'] =date( 'Y-m-d H:i:s',strtotime($info['up_time']));//记账日期
                                $receipt['accountDate'] =$info['up_time'].' 13:13:13';;//记账日期
                                $receipt['bankCode'] = '';//银行代码
                                $receipt['counterContact'] = '';//对方联系人
                                $receipt['bankFlowRemark'] = '';
                                $receipt['lines'] = [
                                    [
                                        'subjectCode' => $costTypeInfo['cost_type_id'],
                                        'amount' => $costInfo['amount'] / 100,
                                        'remark' => '米安贝缴费'
                                    ]
                                ];
                                $HDService = new HaiDing();
                                $result = $HDService->deposit($receipt);
                                $costLogInfo = new CostLog();
                                $costLog['cost_id'] = $costInfo['id'];
                                $costLog['request_info'] = json_encode($receipt);
                                $costLog['responce_info'] = json_encode($result);
                                $costLog['happen_time'] = date('Y-m-d H:i:s', time());
                                $costLog['create_time'] = time();
                                $costLog['update_time'] = time();
                                $costLogInfo->save($costLog);
                                \app\common\model\tang\Cost::update([
                                    'subject_id' => 3,
                                    'pay_status' => 1,
                                    'return_billid' => $result['billNumber'],
                                    'pay_time' => date('Y-m-d H:i:s', time()),
                                    'bill_no' => getBill(),
                                    'amount' => 0,
                                    'pay_amount' => $costInfo['amount'],
                                ], ['id' => $costInfo['id']]);
                            }else{
                                \app\common\model\tang\Cost::update([
                                    'subject_id' => 3,
                                    'pay_status' => 1,
                                    'pay_time' => date('Y-m-d H:i:s', time()),
                                    'bill_no' => getBill(),
                                    'amount' => 0,
                                    'pay_amount' => $costInfo['amount'],
                                ], ['id' => $v]);
                            }
                        }
                    } else {
                        \app\common\model\tang\Cost::update([
                            'subject_id' => 3,
                            'pay_status' => $pay_status,
                        ], ['id' => $v]);
                    }
                }
            } else { //单笔缴费 支持部分缴费
                $costInfo = Cost::find($idArr[0]);
                if ($costInfo['status']==1){
                    return self::JsonReturn('此账单已完成缴费', 0);
                }
                $section = new CostSectionPay(); //分期部分缴费
                if ($pay_status == 1) {
                    $payInfo = [];
                    if ($costInfo['amount'] < $info['in_amount']) {
                        $costMoney = $costInfo['amount'];
                        //多的转移到商户余额中去
//                        return self::JsonReturn('金额高于应支付金额', 0);
                        $duo = bcsub($info['in_amount'], $costInfo['amount']);
                        if($duo>0){
                            $merchantInfo = (new MerchantModel())->find($info['merchant_id']);
                            if (empty($merchantInfo)) {
                                return self::JsonReturn('商户信息不存在', 0);
                            }
                            $bool = BalanceLog::create([
                                'order_sn' => OrderSn(),
                                'mobile' => $merchantInfo['mobile'],
                                'amount' => $duo,
                                'service_charge' => 0,
                                'merchant_id' => $info['merchant_id'],
                                'is_top_up' => 1,
                                'edit' => 1,
                                'type' => 2,
                                'status' => 1,
                                'remark' => '支付订单多出的转账自动冲入余额',
                                'charge_time' => time(),
                                'create_time' => time(),
                            ]);
                            //商户余额自动增加
                            (new MerchantModel())->update(['balance' => bcadd($merchantInfo['balance'], $duo)], ['id' => $merchantInfo['id']]);
                        }
                    }else{
                        $costMoney = $info['in_amount'];
                    }
                    if ($info['in_amount'] >= $costInfo['amount']) {
                        $pay_amount = $costInfo['all_amount'];//已支付金额
                        $amount = 0; //剩余支付金额
                        $section->balance_amount = 0;
                        $now_status = 1;
                    } else {
                        $pay_amount = bcadd($info['in_amount'], $costInfo['pay_amount']);//已支付金额
                        $amount = bcsub($costInfo['amount'], $info['in_amount']); //剩余支付金额
                        $section->balance_amount = bcsub($costInfo['amount'], $info['in_amount']);
                        $now_status = 0;
                    }
                    if (!empty($costInfo['billid'])) {
                        $payInfo['direction'] = 1;
                        $payInfo['paymentMethod'] = 'APP';
                        $payInfo['paymentOrderId'] = $costInfo['order_sn'];
                        $payInfo['dealer'] = [
                            'uuid' => '8a0293a988c2d2120188c32b25870098',
                            'code' => 'mianbei',
                            'name' => '米安贝',
                        ];
                        $payInfo['paymentDate'] = date('Y-m-d H:i:s', time());
                        $payInfo['incomeDate'] = date('Y-m-d H:i:s', time());
                        $payInfo['remark'] = '微信小程序收款';
                        $payInfo['sourceType'] = 'cre_other';
                        $payInfo['lines'] = [
                            [
                                'accId' => $costInfo['billid'],
                                'total' => $costMoney/100,
                                'paymentType' => [
                                    'uuid' => '8a0289aa736f21880173bc84e7a36fa5',
                                    'code' => '002',
                                    'name' => '转账',
                                ],
                                'bankCode' => '',
                                'poundage' => ''
                            ]
                        ];
                        $HDService = new HaiDing();
                        $result = $HDService->payInfo($payInfo);
                        $costLogInfo = new CostLog();
                        $costLog['cost_id'] = $costInfo['id'];
                        $costLog['request_info'] = json_encode($payInfo);
                        $costLog['responce_info'] = json_encode($result);
                        $costLog['happen_time'] = date('Y-m-d H:i:s', time());
                        $costLog['create_time'] = time();
                        $costLog['update_time'] = time();
                        $costLogInfo->save($costLog);
                        \app\common\model\tang\Cost::update([
                            'subject_id' => 3,
                            'pay_status' => $now_status,
                            'return_billid' => $result['billNumber'],
                            'pay_time' => date('Y-m-d H:i:s', time()),
                            'amount' => $amount,
                            'pay_amount' => $pay_amount,
                            'bill_no' => getBill(),
                        ], ['id' => $idArr[0]]);
                    } else {
                        if(in_array($costInfo['cost_type_id'],[51,52,53,54,55,56,57])){
                            $costTypeInfo=[];
                            $receipt = [];
                            $costTypeInfo = (new CostType())->where('id',$costInfo['cost_type_id'])->find();
                            $receipt['unitCode'] = $merchantInfo['store_code'];
                            $receipt['counterpartCode'] = $merchantInfo['tenant_code'];
                            $receipt['dealer'] = [
                                'uuid' => '8a0293a988c2d2120188c32b25870098',
                                'code' => 'mianbei',
                                'name' => '米安贝',
                            ];
                            $receipt['paymentOrderId'] = $costInfo['order_sn']; //订单编号
                            $receipt['contractCode'] = $merchantInfo['code'];//合同号
                            $receipt['paymentTypeCode'] = '002'; //付款方式代码
                            $receipt['depositDate'] =date( 'Y-m-d H:i:s',strtotime($info['up_time'])); //预存日期（收款日期）
                            $receipt['accountDate'] =date( 'Y-m-d H:i:s',strtotime($info['up_time']));//记账日期
                            $receipt['bankCode'] = '';//银行代码
                            $receipt['counterContact'] = '';//对方联系人
                            $receipt['bankFlowRemark'] = '';
                            $receipt['lines'] = [
                                [
                                    'subjectCode' => $costTypeInfo['cost_type_id'],
                                    'amount' => $costMoney / 100,
                                    'remark' => '米安贝缴费'
                                ]
                            ];
                            $HDService = new HaiDing();
                            $result = $HDService->deposit($receipt);
                            $costLogInfo = new CostLog();
                            $costLog['cost_id'] = $costInfo['id'];
                            $costLog['request_info'] = json_encode($receipt);
                            $costLog['responce_info'] = json_encode($result);
                            $costLog['happen_time'] = date('Y-m-d H:i:s', time());
                            $costLog['create_time'] = time();
                            $costLog['update_time'] = time();
                            $costLogInfo->save($costLog);
                            \app\common\model\tang\Cost::update([
                                'subject_id' => 3,
                                'pay_status' => $now_status,
                                'return_billid' => $result['billNumber'],
                                'pay_time' => date('Y-m-d H:i:s', time()),
                                'bill_no' => getBill(),
                                'amount' =>$amount,
                                'pay_amount' => $pay_amount,
                            ], ['id' => $idArr[0]]);
                        }else{
                            \app\common\model\tang\Cost::update([
                                'subject_id' => 3,
                                'pay_status' => $now_status,
                                'pay_time' => date('Y-m-d H:i:s', time()),
                                'amount' => $amount,
                                'pay_amount' => $pay_amount,
                                'bill_no' => getBill(),
                            ], ['id' => $idArr[0]]);
                        }

                    }
                    $section->all_amount = $costInfo['amount'];
                    $section->merchant_id = $costInfo['merchant_id'];
                    $section->cost_id = $costInfo['id'];
                    $section->amount = $info['in_amount'];
                    $section->create_time = time();
                    $section->type = 3;
                    $section->update_time = time();
                    $section->save();
                } else {
                    \app\common\model\tang\Cost::update([
                        'subject_id' => 3,
                        'pay_status' => $pay_status,
                    ], ['id' => $idArr[0]]);
                }
            }
            if ($pay_status == 0) {
                $status = 2;
            }
            if ($pay_status == 1) {
                $status = 1;
            }
            $result = $this->model->update(['status' => $status, 'remark' => $remark], ['id' => $id]);
            Db::commit();
            if ($result) {
                return self::JsonReturn("审核成功");
            }
            return self::JsonReturn('审核失败，请重试', 0);
        }catch (\Exception $exception){
            Db::rollback();
            return self::JsonReturn($exception->getMessage(),0);
        }
        }

}